package cn.wolfcode.common.utils;

import cn.wolfcode.common.exception.WolfCodeException;
import org.apache.commons.io.IOUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtil {

    public static BufferedReader getReaderFromFile(String filePath) throws WolfCodeException {
        try {
            Path path = Paths.get(filePath);

            if (Files.exists(path)) {
                return Files.newBufferedReader(path, StandardCharsets.UTF_8);
            } else {
                throw new WolfCodeException("[" + path.toString() + "] file not exist...");
            }
        } catch (Exception e) {
            throw new WolfCodeException("read file error: " + e.getMessage(), e);
        }
    }

    public static String readLine(BufferedReader reader) throws WolfCodeException {
        try {
            return reader.readLine();
        } catch (IOException e) {
            throw new WolfCodeException("read file error: " + e.getMessage(), e);
        }
    }

    public static String readFile(String filePathStr) throws WolfCodeException {
        try {
            StringBuffer content = new StringBuffer();
            Path path = Paths.get(filePathStr);
            if (Files.exists(path)) {
                BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
                String str = null;
                while ((str = reader.readLine()) != null) {
                    content.append(str);
                }
                IOUtils.closeQuietly(reader);
                return content.toString();
            } else {
                throw new WolfCodeException("[" + path.toString() + "] file not exist...");
            }
        } catch (IOException e) {
            throw new WolfCodeException("read file error: " + e.getMessage(), e);
        }
    }

    public static String readFile(Path filePath) throws WolfCodeException {
        try {
            return new String(Files.readAllBytes(filePath), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new WolfCodeException("read file error: " + e.getMessage(), e);
        }
    }

    public static String readFile(InputStream stream) throws WolfCodeException {
        try {
            StringBuffer content = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String str = null;
            while ((str = reader.readLine()) != null) {
                content.append(str);
            }
            IOUtils.closeQuietly(reader);
            return content.toString();
        } catch (IOException e) {
            throw new WolfCodeException("read file error: " + e.getMessage(), e);
        }
    }
}
